<?php

class _F_EXTENSION_DATA_MODEL_ extends _F_OBJECT_ {
	
	public $_f_db_;
	public $_f_pkey_ = null;
	public $_f_pkey_field_;
	public $_f_table_;
	public $_f_fields_;
	public $_f_autoincrement_ = false;

	public function save() {
		if ($this->_f_pkey_ === null) $this->_f_insert_();
		else $this->_f_update_();
	}
	
	public function _f_insert_() {
		$db = $this->_f_db_;
		$qtable = $this->_f_db_->quote_name($this->_f_table_);
		$pkfield = $this->_f_pkey_field_;
		$fields = $this->_f_fields_;
		$qfields = '';
		$qvalues = '';
		$sep = '';
		if ($this->_f_autoincrement_) 
			$fields = array_diff($fields,array($pkfield));
		foreach ($fields as $field) {
			$qfields .= $sep.$this->_f_db_->quote_name($field);
			$qvalues .= $sep.':'.$field;
			$sep = ',';
		}
		$sql = "INSERT INTO $qtable ($qfields) VALUES ($qvalues)";
		$query = $db->query($sql);
		foreach ($fields as $field) $query->param(':'.$field,$this->$field);
		$query->exec();
		if ($this->_f_autoincrement_) {
			// TODO: not compatible with all PDO driver
			$this->_f_pkey_ = $query->db->connection->lastInsertId();
		} else {
			$this->_f_pkey_ = $this->$pkfield;
		}
	}
	
	public function _f_update_() {
		$db = $this->_f_db_;
		$qtable = $this->_f_db_->quote_name($this->_f_table_);
		$pkfield = $this->_f_pkey_field_;
		$fields = $this->_f_fields_;
		$qfields = '';
		$sep = '';
		foreach ($fields as $field) {
			$qfields .= $sep.$this->_f_db_->quote_name($field).' = :'.$field;
			$sep = ',';
		}
		$qpkf = $this->_f_db_->quote_name($pkfield);
		$sql = "UPDATE $qtable SET $qfields WHERE $qpkf = :_f_pkey_";
		$query = $db->query($sql);
		foreach ($fields as $field) $query->param(':'.$field,$this->$field);
		$query->param(':_f_pkey_',$this->_f_pkey_);
		$query->exec();
		$this->_f_pkey_ = $this->$pkfield;
	}	
	
	public function delete() {
		$db = $this->_f_db_;
		$qtable = $this->_f_db_->quote_name($this->_f_table_);
		$pkfield = $this->_f_pkey_field_;
		$qpkf = $this->_f_db_->quote_name($pkfield);
		$sql = "DELETE FROM $qtable WHERE $qpkf = :_f_pkey_";
		$query = $db->query($sql);
		$query->param(':_f_pkey_',$this->_f_pkey_);
		$query->exec();
		$this->_f_pkey_ = null;
	}	

}
